﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Collections;
using System.Web;
namespace Gammar.Digger.SystemFramework
{

    /// <summary>
    /// The class can set or get application context
    /// Author: Fred Weng
    /// </summary>
    public static class AppContext
    {
        #region AppContext public member

        public static string AppPath = null;            //such as C:\VS2005\Dang\xxx\
        public static string AppName = null;            //such as Dang.Web (WebApplication) or MyApp.exe (win exe)
        public static readonly DateTime DateMinValue = DateTime.Parse("1900-1-1");
        public static readonly DateTime DateMaxValue = DateTime.Parse("2099-12-31");
        public static string AppUrlPrefix = null;   //such as http:/localhost
        public static SortedList ConnectionStringList = null;//save decrypt connection string in web.config

        #endregion

        static AppContext()
        {
            #region static initial

            HttpContext pageContext = HttpContext.Current;
            if (pageContext == null)//windows or console application
            {
                AppDomain domain = AppDomain.CurrentDomain;
                AppPath = domain.BaseDirectory;
                AppName = domain.FriendlyName;

            }
            else //web application
            {
                HttpRequest request = pageContext.Request;
                AppPath = request.PhysicalApplicationPath;
                AppName = request.ApplicationPath.Substring(1);
                AppUrlPrefix = string.Format("http://{0}", request.ServerVariables["HTTP_HOST"]);
            }

            AppContext.ConnectionStringList = new SortedList();
            ConnectionStringSettingsCollection cssc = ConfigurationManager.ConnectionStrings;
#if DEBUG
            for (int i = 1; i < cssc.Count; i++)
            {
                AppContext.ConnectionStringList[cssc[i].Name] = cssc[i].ConnectionString;
            }
#else
            for (int i = 1; i < cssc.Count; i++)
            {
                AppContext.ConnectionStringList[cssc[i].Name] = cssc[i].ConnectionString;
            }
            //for (int i = 1; i < cssc.Count; i++)
            //{
            //    AppContext.ConnectionStringList[cssc[i].Name] = CryptoHelper.Decrypt(cssc[i].ConnectionString, cssc[i].Name);
            //}
#endif
            #endregion
        }

        public static string GetAppSetting(string key)
        {
            return ConfigurationManager.AppSettings[key];
        }
    }
}
